package MediaPlayer;

import com.demiroot.server.Logger;

public class MPlayer implements Player {
	public static String MPLAYER_PATH = "C:\\Documents and Settings\\Sean Oczkowski\\Desktop\\MPlayer-1.0rc1-gui\\MPlayer-1.0rc1-gui\\gmplayer.exe";
	MPlayerThread mpt;
	int volume;
	String file = null;
	boolean fileIsPlaylist = false;
	
	public MPlayer() {
		mpt = null;
		volume = 20;
	}
	
	
	@Override
	public void fullScreen() {
		send("vo_fullscreen");
		
	}

	@Override
	public void fwd() {
		send("seek 10 0");
	}

	@Override
	public void mute() {
		send("mute");
	}

	@Override
	public void next() {
		send("pt_step 1");
	}

	@Override
	public void pause() {
		if (mpt == null) {
			if (!fileIsPlaylist) {
				playFile(file);
			} else {
				playList(file);
			}
		} else {
			send("pause");
			mpt.paused = !mpt.paused;
		}
	}

	@Override
	public void playFile(String file) {
		fileIsPlaylist = false;
		if (mpt != null) {
			mpt.finish();
		}
		mpt = new MPlayerThread(MPLAYER_PATH, file);
		mpt.start();
		send("loadfile " + file);
		this.file = file;
	}

	@Override
	public void playList(String playList) {
		fileIsPlaylist = true;
		if (mpt != null) {
			mpt.finish();
		}
		mpt = new MPlayerThread(MPLAYER_PATH, playList);
		mpt.start();
		this.file = playList;
	}

	@Override
	public void prev() {
		send("pt_step -1");
	}

	@Override
	public void rwd() {
		send("seek -10 0");
	}

	@Override
	public void seek(int place) {
		send("seek " + place + " 2");
		mpt.timePos = place;
	}

	@Override
	public void seek(double percent) {
		send("seek " + percent*100 + " 1");
		mpt.timePos = getLength()*percent;
	}

	@Override
	public void stop() {
		mpt.finish();
		mpt = null;
	}

	@Override
	public void volDown() {
		send("volume -10 0");
				
	}

	@Override
	public void volUp() {
		send("volume 10 0");
	}


	public void send(String cmd) {
		Logger.log("mplayer",cmd);
		if( mpt != null) {
			mpt.send(cmd);
		}
	}

	@Override
	public void exit() {
		mpt.finish();
		file = null;
	}


	@Override
	public boolean isPlaying() {
		if (mpt == null) {
			return false;
		}
		return !mpt.paused;
	}


	@Override
	public String currentlyPlaying() {
		return file;
	}


	@Override
	public double getLength() {
		return mpt.length;
	}


	@Override
	public double getPercentDone() {
		if (mpt == null) {
			return 0;
		}
		return ((double)getPosition())/((double)getLength());
	}


	@Override
	public double getPosition() {
		return mpt.timePos;
	}

}
